<?php

namespace app\api\controller;

use app\admin\model\nursery\Companyattestation;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\library\Sms;
use app\common\model\UserKey;
use fast\Random;
use think\Config;
use think\Db;
use think\Lang;
use think\Log;
use think\Model;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['mobilelogin', 'register','wxLogin','getWxPhone','empower','follow'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 前端授权
     */
    public function empower(){
        $code = $this->request->param("code");
        $result = getOpenid($code);
        if (!isset($result['openid'])) {
            $this->error('授权失败', $result);
        }
        $user = \app\admin\model\User::get(['openid'=>$result['openid']]);
        $job_id = '';
        $realname = '';
        $mobile = '';
        if($user){
            $job_id = $user['job_id'];
            $realname = $user['realname'];
            $mobile = $user['mobile'];
        }else{
            if(!UserKey::get(['openid'=>$result['openid']])){
                $data=[
                    'openid'=>$result['openid'],
                    'session_key'=>$result['session_key']
                ];
                UserKey::create($data);
            }else{
                $data=[
                    'session_key'=>$result['session_key']
                ];
                UserKey::update($data,['openid'=>$result['openid'],]);
            }
        }
        $this->success('授权成功', ['job_id'=>$job_id,'name'=>$realname,'mobile'=>$mobile,'openid'=>$result['openid']]);
    }

    /**
     * 用户登录
     *
     */
    public function wxLogin()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
            ['mobile', 'require', '电话号码不能为空'],
            ['realname', 'require', '姓名不能为空'],
            ['openid', 'require', 'openid不能为空'],
            ['job_id', 'require', '职位不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $openid = $this->request->param("openid");
        $UserKey = UserKey::get(['openid'=>$openid]);
        if (!$openid) {
            $this->error('授权过期,请刷新重新登录');
        }

        $data = [
            "nickname" => $this->request->param("nickname"),
            "avatar" => $this->request->param("avatar"),
            "username"=> $this->request->param("mobile"),
            "mobile"=> $this->request->param("mobile"),
            "realname"=> $this->request->param("realname"),
            "job_id"=> $this->request->param("job_id"),
        ];

        $user = \app\common\model\User::get(['openid' => $openid]);
        if(!$user){
            $user = \app\admin\model\User::get(['mobile' => $data["mobile"]]);
        }
        if (!$user) {
            $data=[
                "username"=> $data["mobile"],
                "user_permissions"=>4,
                "mobile"=> $data["mobile"],
                'status'=>"normal",
                'openid'=>$openid,
                'session_key'=>$UserKey['session_key'],
                'joinip'=>request()->ip(),
                'jointime'=>time(),
                'nickname'=>$data["nickname"],
                'avatar'=>$data["avatar"],
                'job_id'=>$data["job_id"],
                'realname'=>$data["realname"],
                'is_old_user'=>2,
            ];
            $user = \app\admin\model\User::create($data);

        }else{
            if($user['is_old_user'] == 1){
                if($user['job_id'] != $data["job_id"] || $user['name'] != $data["name"]){  //后面用户登录并更新了信息的 都需要验证职位和名称
                    $this->error('用户信息不匹配');
                }
            }
            //存在更新session_key
            \app\admin\model\User::update([
                'session_key'=>$UserKey['session_key'],
                'nickname'=>$data["nickname"],
                'avatar'=>$data["avatar"],
                'job_id'=>$data["job_id"],
                'realname'=>$data["realname"],
                'mobile'=> $data["mobile"],
                'is_old_user'=>2,
            ],['id'=>$user['id']]);
        }
        $ret = $this->auth->direct($user['id']);
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $user2 = \app\common\model\User::get($user["id"]);
            $userinfo = [
                "id" => $user["id"],
                "nickname" => $user["nickname"],
                "avatar" => ImageUtil::handle($user["avatar"]),
                "status" => $user2["status"],
                "mobile" => $user["mobile"],
                'user_per'=> \app\common\common\Common::$userPer[$user2['user_permissions']] ?? [],
                "token" => $user["token"],
                "url" => Request::instance()->domain(),
                "is_bind_wechat_openid" => $user['wechat_openid'] ? 1 : 0
            ];
            $this->success(__('Logged in successful'), $userinfo);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'login')) {
            $this->error(__('Captcha is incorrect'));
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            $user = $this->auth->getUserinfo();
            $user2 = \app\common\model\User::get($user["id"]);
            $userinfo = [
                "id" => $user["id"],
                "nickname" => $user["nickname"],
                "avatar" => ImageUtil::handle($user["avatar"]),
                "status" => $user2["status"],
                "mobile" => $user["mobile"],
                'user_per'=> \app\common\common\Common::$userPer[$user2['user_permissions']] ?? [],
                "token" => $user["token"],
                "url" => Request::instance()->domain()
            ];
            $this->success(__('Logged in successful'), $userinfo);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改用户个人信息
     *
     * @ApiMethod (POST)
     */
    public function profile()
    {
        $user = $this->auth->getUser();
//        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname'); //昵称
        $bio = $this->request->post('bio');
        $gender = $this->request->post('gender'); //性别
        $project_position = $this->request->post('project_position'); //职位
        $job_id = $this->request->post('job_id'); //职位id
        $name = $this->request->post('name'); //真实姓名
        $birthday = $this->request->post('birthday'); //出生年月日
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if($gender){
            $user->gender = $gender;
        }
        if($project_position){
            $user->project_position = $project_position;
        }
        if($job_id){
            $user->job_id = $job_id;
        }
        if($name){
            $user->name = $name;
        }
        if($bio){
            $user->bio = $bio;
        }
        if($avatar){
            $user->avatar =  $avatar;
        }
        if($birthday){
            $user->birthday =$birthday;
        }
//        if ($username) {
//            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Username already exists'));
//            }
//            $user->username = $username;
//        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->save();
        $this->success('修改成功');
    }

    /**
     * 获取用户信息
     * */
    public function getUser()
    {
        $user = $this->auth->getUser();
        $info = \app\common\model\User::field("id,nickname,avatar,mobile,bio,gender,realname,project_position,user_permissions,birthday,job_id")->where(["id" => $user["id"]])->find();
        if($info) {
            $info['user_per']= \app\common\common\Common::$userPer[$info['user_permissions']] ?? [];
        }
        $this->success("成功", $info);
    }


    /**
     * 获取用户微信手机
     * @throws \think\Exception
     */
    public function getWxPhone()
    {
        $tmp = getAccessToken();
        $token = $tmp["access_token"];
        $data['code'] = input('code');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = \fast\Http::post($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info,true);
        if ($tmpinfo["errcode"]  == 0) {
           $userInfo = \app\admin\model\User::get(['mobile'=>$tmpinfo["phone_info"]["purePhoneNumber"]]);
            $this->success(__('Logged in successful'), [
                'mobile'=>$tmpinfo["phone_info"]["purePhoneNumber"],
                'nickname'=> $userInfo['nickname'],
                'avatar'=> $userInfo['avatar'],
                'avatar_url'=> ImageUtil::handle($userInfo['avatar']),
            ]);
        } else {
            $this->error($tmpinfo["errcode"] );
        }
    }


    /**
     * 绑定微信公众号
     */
    public function bindWechat(){
        $user = $this->auth->getUser();
        $wxCode = $this->request->param("wxCode");
        $result = getOpenid2($wxCode);
        if(isset($result['openid'])){
            $result2 = getWechatUserInfo($result['openid']);
            if(isset($result2['subscribe'])){
                $data = [
                    'wechat_openid'=> $result['openid'],
                    'is_follow' =>  $result2['subscribe'],
                    'follow_time' =>  isset($result2['subscribe_time']) ? $result2['subscribe_time'] : 0,
                ];
                \app\admin\model\User::update($data,['id'=>$user['id']]);
                $this->success("绑定成功");
            }
        }
        $this->error("绑定失败");
    }


    /**
     * 微信信息回调
     */
    public function follow(){
        $res = $this->checkSignaTure();
        if($res){
            $postObj = file_get_contents('php://input');
            $postArr = simplexml_load_string($postObj,'SimpleXMLElement',LIBXML_NOCDATA);
            if($postArr->MsgType == "event" && $postArr->Event && in_array($postArr->Event,['subscribe','unsubscribe'])){ //用户关注操作
                if($postArr->Event == "subscribe"){
                    $data =[
                        'is_follow'=>1,
                        'follow_time'=>$postArr->CreateTime,
                    ];
                }else{
                    $data =[
                        'is_follow'=>0,
                        'follow_time'=>null,
                    ];
                }
                \app\admin\model\User::update($data,['wechat_openid'=>$postArr->FromUserName]);
            }
            echo isset($_GET['echostr']) ? $_GET['echostr'] : '';
            exit();
        }else{
            echo '';
            exit();
        }
    }

    /**
     * @return bool
     * 微信回调签名验证
     */
    private function checkSignaTure(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "hdkjfdjsllsd";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }
}
